#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

uint16_t serverport = 8888;
std::string serverip = "82.157.121.141";

int main()
{
    // 初始化Winsock库
    WSAData wsaData;
    int res = WSAStartup(MAKEWORD(2,2),&wsaData);
    if(res != 0)
    {
        std::cerr << "初始化Winsock失败" << std::endl;
        return -1;
    }
    // 创建套接字
    // SOCK_DGRAM用于Udp协议
    // SOCK_STREAM用于Tcp协议
    SOCKET skt = socket(AF_INET,SOCK_DGRAM,0);  
    if(skt == INVALID_SOCKET)
    {
        std::cerr << "创建套接字失败" << std::endl;
        WSACleanup();
        return -1;
    }

    // 配置服务器地址信息
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    int len = sizeof(server);

    // 接收和发送数据
    char message[4096];
    char buffer[4096];
    while(true)
    {
        // 发送
        std::cout << "windows say@: ";
        fgets(message,sizeof(buffer),stdin);
        int send = sendto(skt,message,strlen(message),0,(struct sockaddr*)&server,len);
        if(send == SOCKET_ERROR)
        {
            perror("sendto fail: ");
        }
        // 接收
        struct sockaddr_in temp;
        int len = sizeof(temp);
        int s = recvfrom(skt,buffer,sizeof(buffer),0,(struct sockaddr*)&temp,&len);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << "Linux return@ " << buffer << std::endl;
        }
    }

    // 关闭套接字
    closesocket(skt);
    WSACleanup();

    return 0;
}